<template>
  <!-- 商品列表 不显示在导航中 -->
  <div class="admin_index">
    <div class="back" @click="goback">返回{{parent_title}}</div>
    <div class="back" @click="addGoods">新增商品</div>
    <el-card class="box-card">
      <div class="user_info">
        <el-table :data="tableData" border style="width: 100%">
          <el-table-column prop="name" label="标题" width="100px"></el-table-column>
          <el-table-column prop="desc" label="描述"></el-table-column>
          <el-table-column prop="price" label="价格" width="100px"></el-table-column>
          <el-table-column prop="stock" label="库存" width="100px"></el-table-column>
          <el-table-column prop="img" label="图片">
            <template slot-scope="scope">
              <el-upload
                class="avatar-uploader"
                ref="selfUpload"
                :action="JSON.stringify(scope.row)+'----img'"
                :show-file-list="false"
                :http-request="upload"
              >
                <img v-if="scope.row.img" :src="scope.row.img" class="cover" />
                <i v-else class="el-icon-plus avatar-uploader-icon cover"></i>
              </el-upload>
            </template>
          </el-table-column>
          <el-table-column prop="cover" label="封面">
            <template slot-scope="scope">
              <el-upload
                class="avatar-uploader"
                ref="selfUpload"
                :action="JSON.stringify(scope.row)+'----cover'"
                :show-file-list="false"
                :http-request="upload"
              >
                <img v-if="scope.row.cover" :src="scope.row.cover" class="cover" />
                <i v-else class="el-icon-plus avatar-uploader-icon cover"></i>
              </el-upload>
            </template>
          </el-table-column>
          <el-table-column fixed="right" width="100" label="操作">
            <template slot-scope="scope">
              <el-button type="text" @click="goodAttr(scope.row)">商品规格属性</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 新增 -->
    <el-dialog title="新增" :visible.sync="add_dialog" width="40%" center>
      <el-form :label-position="'left'" label-width="100px" :model="good_form">
        <el-form-item label="名称" required>
          <el-input v-model="good_form.name"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="good_form.desc"></el-input>
        </el-form-item>
        <el-form-item label="图片地址">
          <el-input v-model="good_form.img"></el-input>
        </el-form-item>
        <el-form-item label="封面地址">
          <el-input v-model="good_form.cover"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="add_dialog = false">取 消</el-button>
        <el-button type="primary" @click="add">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 商品属性 -->
    <el-dialog title="规格编辑" :visible.sync="good_attr" width="60%" center>
      <div class="spec_body">
        <div class="tables">
          <div class="sku_list">
            <div class="attr_name">
              <span>规格名称：</span>
              <el-input v-model="new_sku.name" size="mini" style="width:120px"></el-input>
              <span style="margin-left:20px">规格值：</span>
              <template v-for="item in new_sku.values">
                <el-tag
                  :key="item"
                  style="margin-right:10px"
                  closable
                  @close="closeTag(item)"
                >{{item}}</el-tag>
              </template>

              <el-popover placement="bottom" title="新增规格值" width="200" trigger="click">
                <el-input clearable placeholder="请输入规格值" v-model="new_sku_value"></el-input>
                <el-button
                  icon="el-icon-plus"
                  type="primary"
                  style="width:100%;margin-top:10px;"
                  @click="addNewSku"
                >新增</el-button>
                <el-button
                  slot="reference"
                  type="primary"
                  circle
                  icon="el-icon-plus"
                  style="margin-left:10px"
                  size="mini"
                ></el-button>
              </el-popover>

              <el-button
                size="mini"
                type="primary"
                style="margin-left:20px"
                @click="addSkuTable"
              >添加规格</el-button>
            </div>
          </div>
        </div>
        <el-table :data="skuTable" style="margin-top:20px;flex:1" border>
          <el-table-column prop="name" label="规格名称" width="180px"></el-table-column>
          <el-table-column prop="values" label="规格值">
            <template slot-scope="scope">
              <el-tag
                v-for="item in scope.row.values"
                :key="item"
                style="margin-right:10px"
              >{{item}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column fixed="right" width="180" label="操作">
            <template slot-scope="scope">
              <el-button type="success" @click="goodAttr(scope.row)">编辑</el-button>
              <el-button type="danger" @click="goodAttr(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-row style="margin-top:20px">
          <el-button type="success" style="width:100%" @click="saveSkuList">保存规格</el-button>
        </el-row>

        <el-row style="margin-top:20px">
          <el-button type="primary" style="width:100%;" @click="bornSpec">生成规格表</el-button>
        </el-row>

        <el-table :data="spec_table" style="margin-top:20px;flex:1" border>
          <el-table-column prop="product_specs" label="具体规格"></el-table-column>
          <el-table-column prop="stock" label="库存">
            <template slot-scope="scope">
              <el-input v-show="scope.row.edit" size="small" v-model="scope.row.stock"></el-input>
              <span v-show="!scope.row.edit">{{ scope.row.stock }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="价格">
            <template slot-scope="scope">
              <el-input v-show="scope.row.edit" size="small" v-model="scope.row.price"></el-input>
              <span v-show="!scope.row.edit">{{ scope.row.price }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="img" label="展示图片"></el-table-column>
          <el-table-column fixed="right" width="180" label="操作">
            <template slot-scope="scope">
              <el-button
                v-show="!scope.row.edit"
                type="primary"
                @click="scope.row.edit=true"
                size="small"
                icon="edit"
              >编辑</el-button>
              <el-button
                v-show="scope.row.edit"
                type="success"
                @click="complete(scope.row)"
                size="small"
                icon="check"
              >完成</el-button>
              <el-button type="danger" @click="deleteSpec(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row style="margin-top:20px">
          <el-button type="success" style="width:100%;" @click="saveSkuTable">保存规格表</el-button>
        </el-row>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="good_attr = false">取 消</el-button>
        <el-button type="primary" @click="good_attr = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import descartes from "@/utils/index";
export default {
  data() {
    return {
      //规格生成
      sku_list: [],
      //新增规格
      new_sku: {
        name: "",
        values: []
      },
      new_sku_value: "",
      //规格表
      skuTable: [],
      //当前编辑得商品
      cur_good: {},

      good_attr: false,

      attr: "",
      options: [],
      tableData: [],
      parent_title: "",

      add_dialog: false,
      good_form: {
        name: "",
        desc: "",
        img: "",
        cover: ""
      },

      tree_data: [],
      defaultProps: {
        children: "children",
        label: "attr_name",
        value: "attr_name",
        multiple: true
      },
      spec_table: []
    };
  },
  mounted() {
    console.log(this.$route);
    const query = this.$route.query;

    this.parent_title = query.parent;

    this.getPage();
  },
  methods: {
    //上传图片
    async upload(params){
      const list = params.action.split('----')
      const row = JSON.parse(list[0])
      const type = list[1]

      const _file = params.file;
      const isLt2M = _file.size / 1024 / 1024 < 2;

      // 通过 FormData 对象上传文件
      var formData = new FormData();
      formData.append("file", _file);

      if (!isLt2M) {
        this.$message.error("请上传2M以下的文件");
        return false;
      }

      const res = await this.$api.fileApi.upload(formData)
      row[type] = res.data.data;
      const resule = await this.$api.goodsApi.updateSingle(row)
      this.getPage()
    },
    async deleteSpec(row) {
      const res = await this.$api.goodsApi.deleteSpec({ id: row.id });
      console.log(res);
      this.specTablePage();
    },
    //编辑完成
    async complete(row) {
      row.edit = false;
      const res = await this.$api.goodsApi.specUpdate(row);
      console.log(res);
    },
    //保存商品规格表
    async saveSkuTable() {
      const res = await this.$api.goodsApi.goodSpecAdd(this.spec_table);
      console.log(res);
    },
    //保存规格
    async saveSkuList() {
      const id = this.cur_good.id;
      const type = "attr_list";
      const attr_list = JSON.stringify(this.skuTable);
      const data = { id, attr_list };

      const res = await this.$api.goodsApi.updateGood(type, data);
      console.log(res);
    },
    addSkuTable() {
      this.skuTable.push(this.new_sku);
      this.new_sku = { name: "", values: [] };
    },
    //新增规格值
    addNewSku() {
      const sku = this.new_sku;
      const values = sku.values;
      values.push(this.new_sku_value);
      this.new_sku.values = Array.from(new Set(values));
    },
    //删除规格
    closeTag(item) {
      const index = this.new_sku.values.indexOf(item);
    },
    //生成规格表
    bornSpec() {
      let arr = this.skuTable;
      let array = [];
      for (let i in arr) {
        let key = i;
        let value = arr[i];
        let obj_array = [];

        obj_array = value.values.map(item => {
          return `${value.name}:${item}`;
        });
        array.push(obj_array);
      }
      let newarr = descartes(array);

      newarr = newarr.map(item => {
        return {
          product_id: this.cur_good.id,
          product_specs: item.join(","),
          stock: 0,
          price: 0,
          img: "",
          edit: false
        };
      });

      this.spec_table = newarr;
    },
    //查询商品规格表
    async specTablePage() {
      const res = await this.$api.goodsApi.specTablePage({
        product_id: this.cur_good.id
      });

      let tb = res.data.data;
      if (tb) {
        tb.forEach(item => {
          item.edit = false;
        });
        this.spec_table = tb;
      } else {
        this.spec_table = [];
      }
    },
    //商品属性
    goodAttr(row) {
      // this.$router.push({ path:'/cms/user/good_sku',query:{ good:row }})
      this.cur_good = row;

      if (row.attr_list) this.skuTable = JSON.parse(row.attr_list);
      else this.skuTable = [];

      this.good_attr = true;
      this.$nextTick(() => {
        this.specTablePage();
      });
    },
    addGoods() {
      this.add_dialog = true;
    },
    goback() {
      this.$router.back(-1);
    },
    //page
    async getPage() {
      const res = await this.$api.goodsApi.goodPage({
        class_id: this.$route.query.id
      });
      console.log(res);
      this.tableData = res.data.data;
    },
    //添加商品
    async add() {
      this.good_form.class_id = this.$route.query.id;

      const res = await this.$api.goodsApi.addGoods(this.good_form);

      this.getPage();
      this.add_dialog = false;
    }
  }
};
</script>

<style lang="less" scoped>
.sku_list {
  display: flex;
  flex-direction: column;
  .attr_name {
    display: flex;
    align-items: center;
  }
}

.spec_body {
  display: flex;
  flex-direction: column;
}
/deep/.el-tree-node__label {
  margin-left: 10px;
  margin-bottom: 2px;
}
.back {
  display: inline-block;
  padding: 6px 10px;
  margin-bottom: 20px;
  background-color: #3963bc;
  color: #fff;
  margin-right: 20px;
}
.admin_index {
  // min-width: 1280px;
  padding: 20px;
}
.user_info {
  width: 100%;
  display: flex;
  flex-direction: column;
  //   padding-left: 20px;
}

/deep/.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
/deep/.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
/deep/.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
/deep/.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
/deep/.cover {
  width: 180px;
  height: 100px;
  display: block;
}
</style>